package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.GroupInfo;
import com.ruoyi.common.utils.sign.MD5Utils2;
import com.ruoyi.common.utils.tencentUtils.TencentCloudImUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.commons.compress.utils.Lists;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * app用户Controller
 *
 * @author ruoyi
 * @date 2023-02-27
 */
@RestController
@RequestMapping("/system/appuser")
public class AppUserController extends BaseController {
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppTradeRecordService tradeRecordService;
    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    @GetMapping("/getUserAccount")
    public AjaxResult getUserAccount() {
        String account = "";
        Boolean isShow = true;
        while (isShow) {
            String num = CommonUtils.get8LengthId(1);
            Integer isAccount = appUserService.findByAccount(num);
            if (isAccount == 0) {
                account = num;
                isShow = false;
            }
        }
        Map<String, Object> res = new HashMap<>();
        res.put("account", account);
        return success(res);
    }

    /**
     * 查询app用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AppUser appUser) {
        startPage();
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        return getDataTable(list);
    }

    /**
     * 导出app用户列表
     */
    @Log(title = "app用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppUser appUser) {
        List<AppUser> list = appUserService.selectAppUserList(appUser);
        ExcelUtil<AppUser> util = new ExcelUtil<AppUser>(AppUser.class);
        util.exportExcel(response, list, "app用户数据");
    }

    /**
     * 获取app用户详细信息
     */
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        AppUser appUser = appUserService.selectAppUserByUserId(userId);
        JSONArray array = tencentCloudImUtil.getJoinedGroupList(appUser.getAccount());
        if (array != null) {
            List<String> groupId = array.stream().map(item -> ((JSONObject) item).getString("GroupId")).collect(Collectors.toList());
            List<GroupInfo> groupInfos = tencentCloudImUtil.getGroupInfo(groupId);
            appUser.setGroupInfos(groupInfos);
        }
        return success(appUser);
    }

    @Autowired
    private IAppFunctionConfigurationService appFunctionConfigurationService;
    @Autowired
    private IBaseInvitationCodeService iBaseInvitationCodeService;
    @Autowired
    private IAppGroupInfoService iAppGroupInfoService;
    @Autowired
    private IBaseFriendsDefaultService baseFriendsDefaultService;

    /**
     * 新增app用户
     */
    @Log(title = "app用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppUser appUser) {
        BaseInvitationCode invitationCodeInfo = iBaseInvitationCodeService.getOne(new QueryWrapper<BaseInvitationCode>().eq("invitation_code", appUser.getInvitationCode()));
        AppUser userRecord = appUserService.getOneByMobile(appUser.getMobile());
        if (null != userRecord) {
            return error("账号已存在！");
        }
        Date nowTime = new Date();
        /*
         * 保存用户基本信息
         */
        AppUser user = new AppUser();
        Boolean isShow = true;
        String account = "";
        while (isShow) {
            String num = CommonUtils.get8LengthId(1);
            Integer isAccount = appUserService.findByAccount(num);
            if (isAccount == 0) {
                account = num;
                isShow = false;
            }
        }
        user.setIsadd(1L);
        user.setHeadImg(appUser.getHeadImg());
        user.setUserId(Long.parseLong(account));
        user.setCreateTime(nowTime);
        user.setAccount(account);
        user.setUsername(appUser.getUsername());
        user.setMobile(appUser.getMobile());
        user.setInvitationCode(appUser.getInvitationCode());
        user.setPassword(MD5Utils2.getMD5String(appUser.getPassword()));
        user.setLastIp("");
        user.setSex(0);
        appUserService.insertAppUser(user);
        // Start >>>>>>>> 账号加入腾讯云 IM <<<<<<<<<
        tencentCloudImUtil.accountImport(account + "", user.getUsername(), user.getHeadImg());
        // End >>>>>>>> 账号加入腾讯云 IM <<<<<<<<<

        if (invitationCodeInfo != null && StringUtils.isNotEmpty(invitationCodeInfo.getDefaultUser())) {
            String userIds = invitationCodeInfo.getDefaultUser();
            String[] userid = userIds.split(",");
            for (int i = 0; userid != null && i < userid.length; i++) {
                // 添加渠道好友
                tencentCloudImUtil.FRIEND_ADD(account, userid[i]);
                // 发送打招呼信息
                tencentCloudImUtil.sendmsg(userid[i], account, invitationCodeInfo.getSayText());
            }
        }
        // End >>>>>>>> 添加到默认群组里 <<<<<<<<<

        // Start >>>>>>>> 添加到默认群组里 <<<<<<<<<
        List<AppGroupInfo> list = iAppGroupInfoService.list(new QueryWrapper<AppGroupInfo>().eq("is_default", 0));
        List<Map<String, Object>> MemberLists = Lists.newArrayList();
        Map<String, Object> map_user = new HashMap<>();
        map_user.put("Member_Account", account);
        MemberLists.add(map_user);

        for (AppGroupInfo info : list) {
            tencentCloudImUtil.groupsAddUsers(MemberLists, info.getGroupId(), info.getGreetingContext());
        }
        // End >>>>>>>> 添加到默认群组里 <<<<<<<<<

        // Start >>>>>>>> 添加默认好友 <<<<<<<<<
        List<BaseFriendsDefault> friendsDefaults = baseFriendsDefaultService.list();
        for (BaseFriendsDefault friendsDefault : friendsDefaults) {
            tencentCloudImUtil.FRIEND_ADD(account, friendsDefault.getAccount());
        }
        // End >>>>>>>> 添加到默认群组里 <<<<<<<<< 添加到默认群组里
        return success();
    }


    @Log(title = "app用户", businessType = BusinessType.INSERT)
    @PostMapping("addList")
    public AjaxResult addList(@RequestBody List<AppUser> appUsers) {
        for (AppUser info : appUsers) {
            Date nowTime = new Date();
            AppUser userRecord = appUserService.getOneByMobile(info.getMobile());
            if (null != userRecord) {
                continue;
            }
            info.setIsadd(1L);
            info.setHeadImg("/profile/avatar/2023/04/04/默认头像_20230404093638A001.png");
            info.setUserId(Long.parseLong(info.getAccount()));
            info.setCreateTime(nowTime);
            info.setAccount(info.getAccount());
            info.setUsername(info.getUsername());
            info.setMobile(info.getMobile());
            info.setPassword(MD5Utils2.getMD5String(info.getPassword()));
            info.setLastIp("");
            info.setSex(2);
            appUserService.insertAppUser(info);
            // Start >>>>>>>> 账号加入腾讯云 IM <<<<<<<<<
            tencentCloudImUtil.accountImport(info.getAccount() + "", info.getUsername(), info.getHeadImg());
            // End >>>>>>>> 账号加入腾讯云 IM <<<<<<<<<
        }
        return success();
    }

    /**
     * 修改app用户
     */
    @Log(title = "app用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppUser appUser) {
        return toAjax(appUserService.updateAppUser(appUser));
    }

    /**
     * 修改用户状态：0：正常，1：冻结
     *
     * @param appUser 状态
     * @return
     */
    @Log(title = "修改用户状态", businessType = BusinessType.UPDATE)
    @PutMapping("/updateAppUserByState")
    public AjaxResult updateAppUserByState(@RequestBody AppUser appUser) {
        int resCode = appUserService.updateAppUserByState(appUser);
        if (resCode > 0 && 1 == appUser.getState()) {
            // 调用 腾讯云 IM  进行操作
            tencentCloudImUtil.accountKick(appUser.getUserId() + "");
        }
        return toAjax(resCode);
    }

    /**
     * 修改用户密码：
     *
     * @param appUser 密码
     * @return
     */
    @Log(title = "修改用户密码", businessType = BusinessType.UPDATE)
    @PutMapping("/updateAppUserByPassword")
    public AjaxResult updateAppUserByPassword(@RequestBody AppUser appUser) {
        String md5String = MD5Utils2.getMD5String(appUser.getPassword());
        appUser.setPassword(md5String);
        return toAjax(appUserService.updateAppUserByPassword(appUser));
    }


    /**
     * 删除app用户
     */
    @Log(title = "app用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(appUserService.deleteAppUserByUserIds(userIds));
    }

    @GetMapping("/transacRecordlist")
    public TableDataInfo transacRecordlist(AppTradeRecord tradeRecord) {
        startPage();
        List<AppTradeRecord> list = tradeRecordService.listByTradeRecord(tradeRecord);
        return getDataTable(list);
    }
}
